import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/entities/setting_data_entity.dart';
import 'package:finance_app/src/utils/reg_exp_utils.dart';
import 'package:finance_app/src/widgets/bottom_sheet/delete_info_bottom_sheet.dart';
import 'package:finance_app/src/widgets/common/expandable.dart';
import 'package:finance_app/src/widgets/list_item/list_expandable_item.dart';
import 'package:finance_app/src/widgets/list_item/list_header_item.dart';
import 'package:finance_app/src/widgets/input/search_input_field.dart';
import 'package:finance_app/src/widgets/select/normal_radio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import 'default_bottom_sheet.dart';

/// 更改币种
///
/// 返回实体类 SettingDataCurrency
showCurrencyBottomSheet(
  BuildContext context,
  SettingDataCurrency currency,
) async {
  SettingDataCurrency _currentSelectCode = currency;
  if (!Config.canAccessAdvanceFeature) {
    showReadyForUpgradeBottomSheet(context);
    return currency;
  }
  final result = await showDefaultBottomSheet(
    context,
    bottomMargin: 0,
    child: CurrencyBottomSheet(
      value: currency,
      selectCallBack: (data) {
        _currentSelectCode = data;
      },
    ),
    title: S.current.currency,
    isScrollControlled: true,
  );
  if (result != null) {
    return {
      'type': _currentSelectCode,
      ...(result as Map),
    };
  }
  return _currentSelectCode;
}

class CurrencyBottomSheet extends StatefulWidget {
  final SettingDataCurrency value;
  final ValueChanged<SettingDataCurrency> selectCallBack;

  const CurrencyBottomSheet({
    Key key,
    this.value,
    this.selectCallBack,
  }) : super(key: key);

  @override
  _CurrencyBottomSheetState createState() => _CurrencyBottomSheetState();
}

class _CurrencyBottomSheetState extends State<CurrencyBottomSheet> {
  TextEditingController _searchController = TextEditingController();
  FocusNode _searchFocusNode = FocusNode();

  Map<String, List<SettingDataCurrency>> data = {};

  SettingDataCurrency currentSelect;
  List<ExpandableController> expandControllerList = [];

  @override
  void initState() {
    super.initState();
    if (Config.settingData != null) {
      data['Common Currencies'] =
          List<SettingDataCurrency>.from(Config.settingData.commonCurrency);
      data['All Currencies'] =
          List<SettingDataCurrency>.from(Config.settingData.currency);
      expandControllerList = List.generate(
          2,
          (index) => ExpandableController(
                initialExpanded: true,
              ));
    }
    currentSelect = widget.value;
    _searchController.addListener(_handleSearchInput);
  }

  void onChangeSalesTrend(SettingDataCurrency value) {
    if (currentSelect == value) return;
    setState(() {
      currentSelect = value;
    });
    widget.selectCallBack?.call(value);
    Navigator.of(context).pop();
  }

  void _handleSearchInput() {
    setState(() {});
  }

  dynamic _onSearchInputItem(List<SettingDataCurrency> element) {
    String searchInput = _searchController.text;
    List<SettingDataCurrency> data = [];
    for (final item in element) {
      if (RegExpUtils.getSearchRegExp(searchInput).hasMatch(item.key)) {
        data.add(item);
      }
    }
    return data;
  }

  @override
  Widget build(BuildContext context) {
    final height = MediaQuery.of(context).size.height * 0.50;
    List<Widget> slivers;
    if (_searchController.text.isNotEmpty) {
      slivers = data.entries
          .toList()
          .map((e) => buildSliver(e.key, _onSearchInputItem(e.value)))
          .toList();
    } else {
      slivers = data.entries
          .toList()
          .map((e) => buildSliver(e.key, e.value))
          .toList();
    }
    // slivers.add(SliverToBoxAdapter(
    //   child: SizedBox(
    //     height: MediaQuery.of(context).viewInsets.bottom / 2,
    //   ),
    // ));
    return Container(
      height: height,
      // margin: EdgeInsets.only(
      //   bottom: MediaQuery.of(context).viewInsets.bottom / 2,
      // ),
      child: Column(
        children: [
          SizedBox(
            height: getDp(17),
          ),
          SearchInputField(
            key: ValueKey('Search Input'),
            controller: _searchController,
            focusNode: _searchFocusNode,
          ),
          SizedBox(
            height: getDp(17),
          ),
          Expanded(
              child: CupertinoScrollbar(
            child: ListView(
              children: slivers,
            ),
          )),
        ],
      ),
    );
  }

  Widget buildSliver(String title, List<SettingDataCurrency> data) {
    final String _title = title.isEmpty ? "*" : title;
    int index = this.data.keys.toList().indexOf(_title);
    print('index: $index');
    ExpandableController controller = expandControllerList[index];
    return ListExpandableItem(
      controller: controller,
      title: _title,
      content: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children:
            List.generate(data.length, (index) => buildSliverItem(data[index])),
      ),
    );
  }

  // Widget buildSliver(String title, List<SettingDataCurrency> data) =>
  //     SliverStickyHeader(
  //       header: buildSliverHeader(title: title),
  //       sliver: SliverList(
  //         delegate: SliverChildBuilderDelegate(
  //           (context, i) => buildItem(data[i]),
  //           childCount: data.length,
  //         ),
  //       ),
  //     );

  Widget buildSliverItem(SettingDataCurrency e) {
    return PressedOpacityButton(
      onPressed: () => onChangeSalesTrend(e),
      padding: EdgeInsets.symmetric(
        vertical: getDp(12),
        horizontal: getDp(25),
      ),
      child: NormalRadio(
        title: e.name,
        isFix: true,
        isSelect: currentSelect?.key == e?.key,
      ),
    );
  }

  Widget buildSliverHeader({String title}) {
    final String _title = title.isEmpty ? "*" : title;
    return ListHeaderItem(
      title: _title,
    );
  }
}
